package utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.ImageColumns;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Window;

import com.shishi.tech.paipai.application.BaseApplication;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import log.LogManager;
import utils.common.ScreenTools;
import utils.common.TimeUtils;
import utils.commonbean.PhotoAibum;
import utils.commonbean.PhotoItem;

/**
 * 相机 相册工具类
 */
public class PhotoUtil {
    private static Uri mCameraImageUri;

    private static Bitmap mSelectedImage;


    public static String getSDcardDir() {
        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    }


    public static String checkAndMkdirs(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dir;
    }


    public static String getCacheImage() {
        String dir = getSDcardDir() + "mar/image";
        return checkAndMkdirs(dir);
    }

    public static String getSaveImage() {
        String dir = getSDcardDir() + "DCIM/mar";
        return checkAndMkdirs(dir);
    }

    public static String getTmpPath() {
        String dir = getSDcardDir() + "mar/tmp";
        return checkAndMkdirs(dir);
    }

    /**
     * 录音存放位置
     */
    public static String getVoicePath(String name) {
        String dir = checkAndMkdirs(getSDcardDir() + "mar/friendcircle/voice");
//        return dir + "/" + name + ".aac";
        return dir + "/" + name;//隐藏文件后缀名
    }

    /**
     * 视频存放位置
     */
    public static String getVideoPath(String name) {
        String dir = checkAndMkdirs(getSDcardDir() + "mar/friendcircle/video");
//        return dir + "/" + name + ".mp4";
        return dir + "/" + name; //隐藏文件后缀名
    }

    public static String getCacheImage(String name) {
        String dir = getCacheImage();
        String path = dir + "/" + name + ".JPEG";
        //String path = dir + "/" + name;//取消后缀名 隐藏文件
        return path;
    }

    public static String saveImage(String name) {
        String dir = getSaveImage();
        String path = dir + "/" + name + ".JPEG";
        return path;
    }

    public static boolean isFileExist(String path) {
        if (path == null)
            return false;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        return true;
    }

    public static long fileSize(String path) {
        if (path == null)
            return 0;
        File file = new File(path);
        if (!file.exists()) {
            return 0;
        }
        return file.length();
    }

    public static boolean delFile(String path) {
        if (path == null)
            return false;
        File file = new File(path);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

    public static String uuid() {
        //return myUUID();
        return System.currentTimeMillis() + "";
    }

    public static String myUUID() {
        StringBuilder sb = new StringBuilder();
        int start = 48, end = 58;
        appendChar(sb, start, end);
        appendChar(sb, 65, 90);
        appendChar(sb, 97, 123);
        String charSet = sb.toString();
        StringBuilder sb1 = new StringBuilder();
        for (int i = 0; i < 24; i++) {
            int len = charSet.length();
            int pos = new Random().nextInt(len);
            sb1.append(charSet.charAt(pos));
        }
        return sb1.toString();
    }

    public static void appendChar(StringBuilder sb, int start, int end) {
        int i;
        for (i = start; i < end; i++) {
            sb.append((char) i);
        }
    }

    /*
     * 获取图片的字段信息
     */
    private static final String[] STORE_IMAGES = {
            MediaStore.Images.Media.DISPLAY_NAME, // 名称
            MediaStore.Images.Media.DATA,
            MediaStore.Images.Media.LONGITUDE, // 经度
            MediaStore.Images.Media._ID, // id
            MediaStore.Images.Media.BUCKET_ID, // dir id 目录
            MediaStore.Images.Media.BUCKET_DISPLAY_NAME ,// dir name 目录名字,
            MediaStore.Images.Media.DATE_MODIFIED//修改时间
    };

    /*
     * 打开系统相机
     */
    public static void openSimpleCamera(Context context) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_PHOTO_CODE);
    }

    /*
     * 检查sdcard
     */
    public static boolean checkSDcard() {
        String sdStatus = Environment.getExternalStorageState();
        if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
            Log.v("TestFile", "SD card is not avaiable/writeable right now.");
            return false;
        }
        return true;
    }

    /*
     * 创建mar文件夹下 图片
     * 
     * @return
     */
    public static String createMartDirs(String name) {
        try {
            String cardpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Mart/";
            File file = new File(cardpath);
            file.mkdirs();// 创建文件夹
            String filename = file.getPath() + name + ".jpg";
            file = new File(filename);
            file.createNewFile();
            return filename;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /*
     * 保存的图片扫面进相册
     */
    public static void scanImageFile(Context context, String filepath) {
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(new File(filepath));
        intent.setData(uri);
        context.sendBroadcast(intent);
    }

    /*
     * 头像 打开系统相机
     */
    /*public static Uri openCamera(Context context) {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            mCameraImageUri = Uri.fromFile(new File(FileUtil.getImageTmpPath(BaseApplication.UPLOAD_PHOTO_NAME)));
        } else {
            Log.d(context.getString(R.string.sdcard_unuse), context.getString(R.string.sdcard_unuse));
            return null;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri);
        ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_PHOTO_CODE);
        return mCameraImageUri;
    }*/


    /*
     * 头像 打开系统相机
     */
    public static String openCamera(Context context, int requestCode) {
       /* if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            mCameraImageUri = Uri.fromFile(new File(FileUtil.getImageTmpPath(BaseApplication.UPLOAD_PHOTO_NAME)));
        } else {
            Log.d(context.getString(R.string.sdcard_unuse), context.getString(R.string.sdcard_unuse));
            return null;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mCameraImageUri);
        ((Activity) context).startActivityForResult(intent, requestCode);

        return mCameraImageUri;*/
        String mFilePath = null;
        if (!isExistExternalStore()) {
            return null;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getTackPicFilePath();
        if (file != null) {
            Uri uri = Uri.fromFile(file);
            if (uri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            mFilePath = file.getAbsolutePath();
        }
        ((Activity) context).startActivityForResult(intent, requestCode);
        return mFilePath;
    }


    /*
     * 打开相册
     */
    /*public static Uri openMediaStore(Context context) {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            mCameraImageUri = Uri.fromFile(new File(FileUtil.getImageTmpPath(BaseApplication.UPLOAD_PHOTO_NAME)));
        } else {
            Log.d(context.getString(R.string.sdcard_unuse), context.getString(R.string.sdcard_unuse));
            return null;
        }
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image*//*");
        ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_CAPTURE_CODE);
        return mCameraImageUri;
    }*/


    /*
    * 打开相册
    */
    public static void openImage(Context context) {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        i.addCategory("android.intent.category.DEFAULT");
        try {
            ((Activity) context).startActivityForResult(i, StaticVariable.REQ_PERSONAL_CENTER_CAPTURE_CODE);
        } catch (ActivityNotFoundException e) {
            LogManager.getLogger().e("ActivityNotFoundException", e.toString());
        }
    }

    public static void openImage(Context context, int requestCode) {
        Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        i.addCategory("android.intent.category.DEFAULT");
        try {
            ((Activity) context).startActivityForResult(i, requestCode);
        } catch (ActivityNotFoundException e) {
            LogManager.getLogger().e("ActivityNotFoundException", e.toString());
        }
    }

    /*
    * 头像 打开系统相机
    */
    public static String openCameras(Context context) {
        String mFilePath = null;
        if (!isExistExternalStore()) {
            return null;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getTackPicFilePath();
        if (file != null) {
            Uri uri = Uri.fromFile(file);
            if (uri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            mFilePath = file.getAbsolutePath();
        }
        ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_PHOTO_CODE);
        return mFilePath;
    }


    public static String openCameras(Context context, int requestCode) {
        String mFilePath = null;
        if (!isExistExternalStore()) {
            return null;
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = getTackPicFilePath();
        if (file != null) {
            Uri uri = Uri.fromFile(file);
            if (uri != null) {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            }
            mFilePath = file.getAbsolutePath();
        }
        ((Activity) context).startActivityForResult(intent, requestCode);
        return mFilePath;
    }


    /*
     * 打开相册
     */
    /*public static void openMediaStore(Context context, int requestCode) {
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            mCameraImageUri = Uri.fromFile(new File(FileUtil.getImageTmpPath(BaseApplication.UPLOAD_PHOTO_NAME)));
        } else {
            Log.d(context.getString(R.string.sdcard_unuse), context.getString(R.string.sdcard_unuse));
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image*//*");
        ((Activity) context).startActivityForResult(intent, requestCode);
    }*/


    public static void startPhotoZoom(Context context, Uri uri, Uri open) {
        int dp = 450;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);//输出是X方向的比例
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
        intent.putExtra("outputX", dp);//输出X方向的像素
        intent.putExtra("outputY", dp);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, open);
        intent.putExtra("return-data", false);//设置为不返回数据
        ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_CORP_CODE);
    }

    public static void startPhotoZoom(Context context, Uri uri, Uri open, Integer code) {
        int dp = 450;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);// 去黑边
        intent.putExtra("scaleUpIfNeeded", true);// 去黑边
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);//输出是X方向的比例
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高，切忌不要再改动下列数字，会卡死
        intent.putExtra("outputX", dp);//输出X方向的像素
        intent.putExtra("outputY", dp);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, open);
        intent.putExtra("return-data", false);//设置为不返回数据
        if (code == null) {
            ((Activity) context).startActivityForResult(intent, StaticVariable.REQ_PERSONAL_CENTER_CORP_CODE);
        } else {
            ((Activity) context).startActivityForResult(intent, code);
        }
    }

    public static Bitmap getBitmapFromUri(Uri uri, Context mContext) {
        try {
            // 读取uri所在的图片
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static Bitmap centerSquareScaleBitmap(Bitmap bitmap, int edgeLength) {
        if (null == bitmap || edgeLength <= 0) {
            return null;
        }

        Bitmap result = bitmap;
        int widthOrg = bitmap.getWidth();
        int heightOrg = bitmap.getHeight();

        if (widthOrg > edgeLength && heightOrg > edgeLength) {
            // 压缩到一个最小长度是edgeLength的bitmap
            int longerEdge = (int) (edgeLength * Math.max(widthOrg, heightOrg) / Math.min(widthOrg, heightOrg));
            int scaledWidth = widthOrg > heightOrg ? longerEdge : edgeLength;
            int scaledHeight = widthOrg > heightOrg ? edgeLength : longerEdge;
            Bitmap scaledBitmap;

            try {
                scaledBitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
            } catch (Exception e) {
                return null;
            }

            // 从图中截取正中间的正方形部分。
            int xTopLeft = (scaledWidth - edgeLength) / 2;
            int yTopLeft = (scaledHeight - edgeLength) / 2;

            try {
                result = Bitmap.createBitmap(scaledBitmap, xTopLeft, yTopLeft, edgeLength, edgeLength);
                scaledBitmap.recycle();
            } catch (Exception e) {
                return null;
            }
        }

        return result;
    }

    /*
     * 图片圆角
     */
    public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }

    /**
     * 重绘视频缩略图
     *
     * @param context
     * @param bitmap
     * @return
     */
    public static Bitmap toNormalBitmap(Context context, Bitmap bitmap) {
        float vedioRatio = (720 * 1.0f) / 480;//视频的分辨率
        float changeRatio = ScreenTools.getInstance(context).getWHRatio() / vedioRatio;//图片转换比例
        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), (int) (bitmap.getHeight() * changeRatio + 0.5f), Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
        paint.setAntiAlias(true);
        Rect srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        Rect desRect = new Rect(0, 0, bitmap.getWidth(), (int) (bitmap.getHeight() * changeRatio + 0.5f));

        canvas.drawBitmap(bitmap, srcRect, desRect, paint);
        return output;
    }

    /*
     * 图片剪切
     */
    public static Bitmap toCutPhoto(Bitmap bitmap) {
        int picHeight = (int) (bitmap.getHeight() / 1.5);
        // 从源图片中截取需要的部分
        return toCutPhoto(bitmap, picHeight);
    }

    /*
     * 图片剪切
     */
    public static Bitmap toCutPhoto(Bitmap bitmap, int displayHeight) {
        return toCutPhoto(bitmap, 0, 0, bitmap.getWidth(), displayHeight);
    }

    /*
     * 图片剪切
     */
    public static Bitmap toCutPhoto(Bitmap bitmap, int displayWidth, int displayHeight) {
        return toCutPhoto(bitmap, 0, 0, displayWidth, displayHeight);
    }

    /*
     * 图片剪切
     */
    public static Bitmap toCutPhoto(Bitmap bitmap, int x, int y, int displayWidth, int displayHeight) {
        // 从源图片中截取需要的部分
        return Bitmap.createBitmap(bitmap, x, y, displayWidth, displayHeight);
    }


    /**
     * 视频缩略图裁剪
     *
     * @param bitmap
     * @param mContext
     * @return
     */
    public static Bitmap toCutPhoto(Context mContext, Bitmap bitmap) {
        // 从源图片中截取需要的部分
        int displayHeight = ScreenTools.getInstance(mContext).getScreenWidth() * 3 / 4;
        //int displayHeight = (int) (ScreenTools.getInstance(mContext).getScreenHeight() - ScreenTools.dpToPx(mContext, 320f));
        int scale = ScreenTools.getInstance(mContext).getScreenHeight() / bitmap.getHeight();
        int y = (int) ScreenTools.dpToPx(mContext, 20f);
        return toCutPhoto(bitmap, 0, y / scale, bitmap.getWidth(), displayHeight / scale);
    }

    /**
     * 视频缩略图裁剪
     *
     * @param bitmap
     * @param mContext
     * @return
     */
    public static Bitmap toCutThumbnail(Context mContext, Bitmap bitmap) {
        //        return toCutPhoto(mContext, toNormalBitmap(mContext, bitmap));
        return bitmap;
    }


    /**
     * 裁剪bitmap 到指定的比例(按最大的比例边 算)
     *
     * @param bitmap
     * @return
     */
    public static Bitmap zoomBitmapToOder(Context context, Bitmap bitmap, int widht, int height) {
        Rect outRect = new Rect();//状态栏高度
        ((Activity) context).getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect);
        int contentTop = ((Activity) context).getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();//标题栏高度

        double bitmapProportion = (double) bitmap.getWidth() / (double) bitmap.getHeight(); //图片 高度和宽度的比例
        double screenProportion = (double) widht / (double) (height);//手机屏幕 高度和宽度的比例

        if (bitmapProportion > screenProportion) {//裁剪的宽 高
            int indexW = (int) (bitmap.getHeight() * screenProportion);//裁剪图片的宽度
            int startW = (bitmap.getWidth() - indexW) / 2;//裁剪图片的中间部分  起始的位置
            bitmap = toCutPhoto(bitmap, startW, 0, indexW, bitmap.getHeight());
        } else {
            int indexH = (int) (bitmap.getWidth() / screenProportion);//裁剪图片的高度
            int startH = (bitmap.getHeight() - indexH) / 2;//裁剪图片的中间部分  起始的位置
            bitmap = toCutPhoto(bitmap, 0, startH, bitmap.getWidth(), indexH);
        }

        return bitmap;
    }

    /*
     * 根据地址 获取bitmap
     */
    private Bitmap getBitmap(String path) {
        File file = new File(path);
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(file);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /*
     * 根据uri 获取bitmap
     */
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        Bitmap bitmap;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            return bitmap;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取网络图像的bitmap
     *
     * @param imageUri
     * @return
     */
    public static Bitmap getbitmapFromURL(String imageUri) {
        // 显示网络上的图片
        Bitmap bitmap = null;
        try {
            URL myFileUrl = new URL(imageUri);
            HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
            conn.setDoInput(true);
            conn.connect();
            InputStream is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            is.close();
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            bitmap = null;
        } catch (IOException e) {
            e.printStackTrace();
            bitmap = null;
        }
        return bitmap;
    }

    public static String getRealPathFromURI(Context context, Uri contentUri) {
        String res = null;
        if (contentUri.toString().startsWith("file")) {//修复小米手机无法返回正确路径
            res = contentUri.getPath();
        } else {
            String[] proj = {MediaStore.Images.Media.DATA};
            Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            if (null == cursor) {
                return null;
            }
            if (cursor.moveToFirst()) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                res = cursor.getString(column_index);
            }
            cursor.close();
        }
        return res;
    }

    public static String getRealPathFromURIForLocal(Context context, Uri contentUri) {
        if (null == contentUri)
            return null;
        final String scheme = contentUri.getScheme();
        String data = null;
        if (scheme == null)
            data = contentUri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = contentUri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(contentUri, new String[]{ImageColumns.DATA}, null,
                    null,
                    null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /*
     * 按相册获取图片信息
     */
    public static Map<String,Object> getPhotoAlbum(Context context) {
        Map<String,Object> map = new HashMap<>();
        List<PhotoAibum> aibumList = new ArrayList<PhotoAibum>();
        List<PhotoItem> allPhoto = new ArrayList<PhotoItem>();
        Cursor cursor = MediaStore.Images.Media.query(context.getContentResolver(),
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, STORE_IMAGES,null,
                MediaStore.Images.Media.DATE_MODIFIED+" desc");
        Map<String, PhotoAibum> countMap = new HashMap<String, PhotoAibum>();
        PhotoAibum pa = null;
        PhotoItem po = null;
        while (cursor.moveToNext()) {
            String path = cursor.getString(1);
            //小米3查询出来的path会出现文件不存在的情况，所以先判断一下文件是否存在，存在才添加
            File file = new File(path);
            if (file.exists()) {
                String id = cursor.getString(3);
                String dir_id = cursor.getString(4);
                String dir = cursor.getString(5);
                String data = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATE_MODIFIED));
                LogManager.getLogger().i("PHOTO = 》", dir_id);
                LogManager.getLogger().i("PHOTO = 》", dir);
                allPhoto.add(new PhotoItem(Integer.valueOf(id), path));
                if (!countMap.containsKey(dir_id)) {
                    pa = new PhotoAibum();
                    pa.setName(dir);
                    pa.setBitmap(Integer.parseInt(id));
                    pa.setCount("1");
                    pa.getBitList().add(new PhotoItem(Integer.valueOf(id), path));
                    countMap.put(dir_id, pa);
                } else {
                    pa = countMap.get(dir_id);
                    pa.setCount(String.valueOf(Integer.parseInt(pa.getCount()) + 1));
                    pa.getBitList().add(new PhotoItem(Integer.valueOf(id), path));
                }
            }
        }
        cursor.close();
        Iterable<String> it = countMap.keySet();
        for (String key : it) {
            aibumList.add(countMap.get(key));
        }
        map.put("album",aibumList);
        map.put("allPhoto",allPhoto);
        return map;
    }

    /**
     * getVideoThumbnail  获取视频缩略图
     *
     * @return Object 返回对象描述
     * @Exception 异常描述
     */
    @SuppressLint("NewApi")
    public static Bitmap getVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }

    /**
     * 获取sha1的值
     *
     * @param context
     * @return
     */
    public static String getSHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);

            byte[] cert = info.signatures[0].toByteArray();

            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
                hexString.append(":");
            }
            return hexString.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param context
     * @param intent
     * @param appPath
     * @return
     */
    public static String resolvePhotoFromIntent(Context context, Intent intent, String appPath) {
        if (context == null || intent == null || appPath == null) {
            return null;
        }
        Uri uri = Uri.parse(intent.toURI());
        Cursor cursor = context.getContentResolver().query(uri, null, null,
                null, null);
        try {

            String pathFromUri = null;
            if (cursor != null && cursor.getCount() > 0) {
                cursor.moveToFirst();
                int columnIndex = cursor
                        .getColumnIndex(MediaStore.MediaColumns.DATA);
                // if it is a picasa image on newer devices with OS 3.0 and up
                if (uri.toString().startsWith(
                        "content://com.google.android.gallery3d")) {
                    // Do this in a background thread, since we are fetching a
                    // large image from the web
                    pathFromUri = saveBitmapToLocal(appPath,
                            createChattingImageByUri(intent.getData()));
                } else {
                    // it is a regular local image file
                    pathFromUri = cursor.getString(columnIndex);
                }
                cursor.close();
                return pathFromUri;
            } else {

                if (intent.getData() != null) {
                    pathFromUri = intent.getData().getPath();
                    if (new File(pathFromUri).exists()) {
                        return pathFromUri;
                    }
                }

                // some devices (OS versions return an URI of com.android
                // instead of com.google.android
                if ((intent.getAction() != null)
                        && (!(intent.getAction().equals("inline-data")))) {
                    // use the com.google provider, not the com.android
                    // provider.
                    // Uri.parse(intent.getData().toString().replace("com.android.gallery3d","com.google.android.gallery3d"));
                    pathFromUri = saveBitmapToLocal(appPath, (Bitmap) intent.getExtras().get("data"));
                    return pathFromUri;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return null;
    }

    /**
     * save image from uri
     *
     * @param outPath
     * @param bitmap
     * @return
     */
    public static String saveBitmapToLocal(String outPath, Bitmap bitmap) {
        try {
            String imagePath = outPath + AESEncryptUtils.md5String(DateFormat.format("yyyy-MM-dd-HH-mm-ss", System.currentTimeMillis()).toString()) + ".jpg";
            File file = new File(imagePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, bufferedOutputStream);
            bufferedOutputStream.close();
            return imagePath;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param uri
     * @return
     */
    public static Bitmap createChattingImageByUri(Uri uri) {
        return createChattingImage(0, null, null, uri, 0.0F, 400, 800);
    }


    /**
     * @param resource
     * @param path
     * @param b
     * @param uri
     * @param dip
     * @param width
     * @param height
     * @return
     */
    public static Bitmap createChattingImage(int resource, String path,
                                             byte[] b, Uri uri, float dip, int width, int height) {
        if (width <= 0 || height <= 0) {
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        int outWidth = 0;
        int outHeight = 0;
        int sampleSize = 0;
        try {

            do {
                if (dip != 0.0F) {
                    options.inDensity = (int) (160.0F * dip);
                }
                options.inJustDecodeBounds = true;
                decodeMuilt(options, b, path, uri, resource);
                //
                outWidth = options.outWidth;
                outHeight = options.outHeight;

                options.inPreferredConfig = Bitmap.Config.ARGB_8888;
                if (outWidth <= width || outHeight <= height) {
                    sampleSize = 0;
                    setInNativeAlloc(options);
                    Bitmap decodeMuiltBitmap = decodeMuilt(options, b, path,
                            uri, resource);

                    int degree = BitmapHelper.getDegress(path);
                    if (degree > 0) {
                        decodeMuiltBitmap = BitmapHelper.rotateBitmap(decodeMuiltBitmap, degree);
                    }

                    return decodeMuiltBitmap;
                } else {
                    options.inSampleSize = (int) Math.max(outWidth / width,
                            outHeight / height);
                    sampleSize = options.inSampleSize;
                }
            } while (sampleSize != 0);

        } catch (IncompatibleClassChangeError e) {
            e.printStackTrace();
            throw ((IncompatibleClassChangeError) new IncompatibleClassChangeError(
                    "May cause dvmFindCatchBlock crash!").initCause(e));
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            BitmapFactory.Options catchOptions = new BitmapFactory.Options();
            if (dip != 0.0F) {
                catchOptions.inDensity = (int) (160.0F * dip);
            }
            catchOptions.inPreferredConfig = Bitmap.Config.RGB_565;
            if (sampleSize != 0) {
                catchOptions.inSampleSize = sampleSize;
            }
            setInNativeAlloc(catchOptions);
            try {
                return decodeMuilt(options, b, path, uri, resource);
            } catch (IncompatibleClassChangeError twoE) {
                twoE.printStackTrace();
                throw ((IncompatibleClassChangeError) new IncompatibleClassChangeError(
                        "May cause dvmFindCatchBlock crash!").initCause(twoE));
            } catch (Throwable twoThrowable) {
                twoThrowable.printStackTrace();
            }
        }

        return null;
    }

    public static void setInNativeAlloc(BitmapFactory.Options options) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                BitmapFactory.Options.class.getField("inNativeAlloc")
                        .setBoolean(options, true);
                return;
            } catch (Exception e) {
            }
        }
    }

    /**
     * @param options
     * @param data
     * @param path
     * @param uri
     * @param resource
     * @return
     */
    public static Bitmap decodeMuilt(BitmapFactory.Options options,
                                     byte[] data, String path, Uri uri, int resource) {
        try {

            if (!checkByteArray(data) && TextUtils.isEmpty(path) && uri == null
                    && resource <= 0) {
                return null;
            }

            if (checkByteArray(data)) {
                return BitmapFactory.decodeByteArray(data, 0, data.length,
                        options);
            }

            if (uri != null) {
                InputStream inputStream = BaseApplication.getInstance()
                        .getContentResolver().openInputStream(uri);
                Bitmap localBitmap = BitmapFactory.decodeStream(inputStream,
                        null, options);
                inputStream.close();
                return localBitmap;
            }

            if (resource > 0) {
                return BitmapFactory.decodeResource(BaseApplication.getInstance()
                        .getResources(), resource, options);
            }
            return BitmapFactory.decodeFile(path, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static boolean checkByteArray(byte[] b) {
        return b != null && b.length > 0;
    }

    /**
     * 是否有外存卡
     *
     * @return
     */
    public static boolean isExistExternalStore() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    public static File getTackPicFilePath() {
        String index = AESEncryptUtils.md5String(TimeUtils.getCurrentTimeLong() + (int) (Math.random() * 1000));
        File localFile = new File(getExternalStorePath() + "/mar/tmp", index + "temp.jpg");
        //File localFile = new File(getExternalStorePath() + "/mar/tmp", index + "temp");//取消后缀名 隐藏文件
        if ((!localFile.getParentFile().exists())
                && (!localFile.getParentFile().mkdirs())) {
            localFile = null;
        }
        return localFile;
    }

    public static File getCopFilePath() {
        String index = AESEncryptUtils.md5String(TimeUtils.getCurrentTimeLong() + (int) (Math.random() * 1000));
        File localFile = new File(getExternalStorePath() + "/mar/tmp", index + "tempCop.jpg");
        //File localFile = new File(getExternalStorePath() + "/mar/tmp", index + "tempCop");//取消后缀名 隐藏文件
        if ((!localFile.getParentFile().exists()) && (!localFile.getParentFile().mkdirs())) {
            try {
                localFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return localFile;
    }

    /**
     * 外置存储卡的路径
     *
     * @return
     */
    public static String getExternalStorePath() {
        if (isExistExternalStore()) {
            return Environment.getExternalStorageDirectory().getAbsolutePath();
        }
        return null;
    }

    /**
     * 检测 文件地址是否是网络文件
     *
     * @param filepath
     * @return
     */
    public static boolean isQiniuFilePath(String filepath) {
        if (TextUtils.isEmpty(filepath)) return false;
        if (filepath.contains(StaticVariable.DOMAIN_QINIU)) {
            return true;
        }
        return false;
    }

    public static String circleLocalPath(String string){
        if (TextUtils.isEmpty(string)) return null;
        int fileindex = string.lastIndexOf("/") + 1;
        return PhotoUtil.getVoicePath(string.substring(fileindex, string.length() - 4));
    }
}
